package com.slfx.open.api.controller;

import cn.hutool.core.lang.UUID;
import com.slfx.open.api.entity.AppSecret;
import com.slfx.open.api.service.AppSecretService;
import com.slfx.open.api.utils.RSAEncrypt;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.security.NoSuchAlgorithmException;
import java.util.Map;


/**
 * @Author: slfx
 * @Date: 2022-09-30
 * @Description: AppSecretController
 **/
@RestController
@RequestMapping("/appSecret")
@Slf4j
public class AppSecretController {

    @Resource
    private AppSecretService appSecretService;

    /**
     * 根据ID获取
     *
     * @param id
     * @return
     */
    @GetMapping("/getById")
    public AppSecret getById(@RequestParam("id") Long id) {
        AppSecret appSecret = appSecretService.getById(id);
        return appSecret;
    }

    @PostMapping("/save")
    public boolean save(@RequestBody AppSecret appSecret) {
        //生成对应的公钥和私钥保存到数据库
        try {
            Map<Integer, String> keyMap = RSAEncrypt.genKeyPair();
            appSecret.setPublicKey(keyMap.get(0));
            appSecret.setPrivateKey(keyMap.get(1));
            appSecret.setAppId(UUID.fastUUID().toString().replace("-", ""));
        } catch (NoSuchAlgorithmException e) {
            log.error("rsa加密获取异常:{}", e);
        }
        boolean save = appSecretService.save(appSecret);
        return save;
    }

}
